package com.sx.shop.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sx.shop.entity.StoreProduct;
import com.sx.shop.entity.User;
import com.sx.shop.mapper.StoreProductMapper;
import com.sx.shop.vo.ResultVo;
import com.sx.shop.vo.StoreChangeVo;
import com.sx.shop.vo.StoreProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class StoreProductService{
    //依赖注入
    @Autowired
    private StoreProductMapper storeProductMapper;

    public ResultVo selectStoreProduct(Integer storeId,String keyword, Integer page, Integer limit) {
        ResultVo vo = new ResultVo();

        PageHelper.startPage( page , limit);//代码下的第一个查询，有分页效果
        List<StoreProductVo> list = storeProductMapper.selectStoreProduct(storeId,keyword);

        PageInfo<StoreProductVo> pageInfo = new PageInfo<>(list);
        vo.setData(list);
        vo.setCount(pageInfo.getTotal());
        return vo;
    }

    public ResultVo selectStoreChangeByStoreId(Integer storeId, String keyword, Integer page, Integer limit) {
        ResultVo vo = new ResultVo();

        PageHelper.startPage( page , limit);//代码下的第一个查询，有分页效果
        List<StoreChangeVo> list = storeProductMapper.selectStoreChangeByStoreId(storeId,keyword);

        PageInfo<StoreChangeVo> pageInfo = new PageInfo<>(list);
        vo.setData(list);
        vo.setCount(pageInfo.getTotal());
        return vo;
    }

    @Transactional
    public void doAdd(StoreProduct storeProduct) {
        storeProductMapper.insert(storeProduct);

        storeProductMapper.insertChange(storeProduct.getStore().getId(),storeProduct.getProduct().getId(),storeProduct.getNum(),"购入",new Date());
    }

    @Transactional
    public void doDel(StoreProduct storeProduct) {
        storeProductMapper.delete(storeProduct.getId());
        storeProductMapper.insertChange(storeProduct.getStore().getId(),storeProduct.getProduct().getId(),storeProduct.getNum(),"销售出",new Date());
    }

    @Transactional
    public void doSave(StoreProduct storeProduct,Integer changeNum) {
        String type="销售出";
        storeProductMapper.update(storeProduct.getId(),storeProduct.getNum());
        if(changeNum>=0){
            type="购入";
        }
//        修改的数量(为实现接口统一，实际意义错误)
        storeProduct.setNum(changeNum);

        storeProductMapper.insertChange(storeProduct.getStore().getId(),storeProduct.getProduct().getId(),storeProduct.getNum(),type,new Date());
    }


}
